﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommonShop.Service.Helper;
using CommonShop.Service;
using NHibernate;

namespace CommonShop.Web.Areas.Manage.Controllers
{
    public class MemberController : Controller
    {
        ISessionFactory serviceFactory = null;
        public MemberController()
        {
            serviceFactory = FluentSessionFactory.GetCurrentFactory();
        }
        //var factory = FluentSessionFactory.GetCurrentFactory();
        //
        // GET: /Manage/Member/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserList()
        {

            using (var session = serviceFactory.OpenSession())
            {
                IList<User> userList = session.CreateQuery("from User").List<User>();
                return View(userList.ToList());
            }

            
        }

        public ActionResult Edit(Guid? UserId)
        {
            if (UserId != Guid.Empty)
            {
                using (var session = serviceFactory.OpenSession())
                {
                    IList<User> userList = session.CreateQuery(string.Format(@"from User where UserId = '{0}'", @UserId)).List<User>();
                    if (userList.Count > 0)
                    {
                        return View(userList[0]);
                    }
                    else
                    {
                        return View();
                    }
                }
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                using (var session = serviceFactory.OpenSession())
                {
                    
                    session.Update(user);
                    session.Flush();
                    return View(user);
                }
            }
            else
            {
                return View();
            }
        }

        public ActionResult Delete(Guid UserId)
        {
            if (UserId != Guid.Empty)
            {
                using (var session = serviceFactory.OpenSession())
                {
                    User user = session.Get<User>(UserId);
                    session.Delete(user);
                    session.Flush();
                    return RedirectToAction("UserList");
                }
                
            }
            else
            {
                return RedirectToAction("UserList");
            }
        }
    }
}
